using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Configuration;
using WebapiTemplate.Infrastructure.Identity;
using Microsoft.Extensions.DependencyInjection;
using WebapiTemplate.Infrastructure.Persistence;
using WebapiTemplate.Application.Common.Interface;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using WebapiTemplate.Application.JwtConfigurationModel;

using WebapiTemplate.Infrastructure.Persistence.Repository;
using WebapiTemplate.Infrastructure.File;

/// <summary>
/// 此类是代替了Startup.cs类
/// </summary>
namespace WebapiTemplate.Infrastructure
{
    public static class DependencyInjection
    {
        //获取Program.cs类中传入的参数
        public static IServiceCollection AddInfrastructure(
            this IServiceCollection services,
            IConfiguration configuration
        )
        {
            //注入数据库依赖
            
            //链接数据库
            services.AddDbContext<WebapiDbcontext>(options =>
            {
                //1、Sqlserver数据库
                //var constr = configuration.GetConnectionString("SqlServer"); //从appsettings.json中获取SqlServer---"SqlServer": "server=.;database=webapidatabase10;uid=sa;pwd=123456;"
                //options.UseSqlServer(constr);//需要该项目引用<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.6" />


                //2、PostreSql数据库
                options.UseNpgsql(
                configuration.GetConnectionString("PostgreSQL"),
                b => b.MigrationsAssembly(typeof(WebapiDbcontext).Assembly.FullName));//"PostgreSQL":"server=host.9ihub.com;database=admin2022_soft2;uid=postgres;pwd=qq_112358;"
            });





            //注入表接口和实现类依赖
            services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));




            //token服务依赖注入
            services.AddTransient<IIdentityService, IdentityService>();




            //注入文件File操作接口和实现类依赖
            services.AddScoped(typeof(IFileService), typeof(FileService));




            //SessionUser解析Claim服务依赖注入
            services.AddHttpContextAccessor();
            services.AddTransient<ISessionUserService, SessionUserService>();




            //获取生产token的配置
            var jwtSetting = configuration.GetSection("JwtSetting").Get<JwtParameterModel>();
            //验证token
            services
                .AddAuthentication(options =>
                {
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(
                            Encoding.UTF8.GetBytes(jwtSetting.Secret)
                        ),
                        ValidateIssuer = false,
                        ValidateAudience = false,
                        ValidateLifetime = true,
                        //注意这是缓冲过期时间，总的有效时间等于这个时间加上jwt的过期时间，如果不配置，默认是5分钟
                        ClockSkew = TimeSpan.FromMinutes(0)
                    };
                });


            //返回一个任务艰巨的services    
            return services;
        }
    }
}
